package org.bootstrap.service.Impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.bootstrap.mapper.TabMapper;
import org.bootstrap.service.TabService;
import org.bootstrap.tool.Tool;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
@Lazy
@Service
public class TabServiceImpl implements TabService {
    @Resource
    private TabMapper tabMapper;

    @Resource
    private Tool tool;

    @Override
    public ArrayList<HashMap<String, Object>> query_all() {
        return tabMapper.query_all();
    }

    /**
     * @param map {name:名字,menu_id:随机ID, }
     * @return int 行数
     */
    @Override
    public int insert_tab(HashMap<String, Object> map) {
        if (map.isEmpty()) {
            return 0;
        }
        return tabMapper.insert_tab(map);
    }

    /**
     * @param data [<>]
     * @return int
     */
    @Override
    public int insert_tab_child(ArrayList<HashMap<Object, Object>> data) {
        if (data.isEmpty()) {
            return 0;
        }
        return tabMapper.insert_tab_child(data);
    }

    @Override
    public JSONObject tab_rename(HashMap<String, Object> body) {
        JSONObject res = JSONUtil.createObj();
        int code;
        if (body.isEmpty()) {
            return null;
        }
        int rows = tabMapper.tab_rename(body);
        if (rows == 1) {
            code = 200;
        } else {
            code = 500;
        }
        res.putOnce("code", code)
                .putOpt("update_time", tool.get_time_str());
        return res;
    }

    @Override
    public JSONObject tab_del(HashMap<String, Object> body) {
        JSONObject res = JSONUtil.createObj();
        int code;
        String msg;
        if (body.isEmpty() || !body.containsKey("id")) {
            code = 500;
            msg = "参数错误";
        } else {
            String id = StrUtil.toString(body.get("id"));// 获取参数
            boolean drop = BooleanUtil
                    .toBoolean(StrUtil
                            .toString(body.getOrDefault("drop", "false")));// 彻底删除数据 默认为false
            if (StrUtil.isNotEmpty(id)) {
                int rows = drop ? tabMapper.tab_del(id) : tabMapper.vm_tab_del(id);
                if (rows > 0) {
                    code = 200;
                    msg = "删除成功";
                } else {
                    code = 500;
                    msg = "删除失败";
                }
            } else {
                code = 500;
                msg = "参数错误";
            }
        }
        res.putOpt("code", code)
                .putOpt("msg", msg);
        return res;
    }
}
